/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.ItemManager;

import utilities.DBConnector;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import resource.Item;
import resource.Macro;
import utilities.Codecs;
import utilities.Helper;
import utilities.Prompt;
/**
 *
 * @author jiaf
 */
public class IM_Add extends ItemManagerBase {
    /**
     * Creates new form IM_Add
     * @param dbSession
     * @param itemTable
     */
    public IM_Add(DBConnector dbSession, javax.swing.JTable itemTable) {
        super(dbSession);
        initComponents();
        setTargetTable(itemTable);
        Helper.loadOptions(dbSession, Macro.DB_CATEGORY, Macro.CATEGORY_NAME_L,
                categoryOption);
        if (!dbSession.check(Macro.DB_ITEM)){
            Prompt.warning(String.format("The table: %s does not exist.",
                    Macro.DB_ITEM));
        }
        regDateField.setText(Helper.getToday());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        notesField = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        authorField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        publisherField = new javax.swing.JTextField();
        publishYearField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        cancelButton = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        clearButton = new javax.swing.JButton();
        callNumField = new javax.swing.JTextField();
        addButton = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        isbnField = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        regDateField = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        categoryOption = new javax.swing.JComboBox();
        nameField = new javax.swing.JTextField();
        priceField = new javax.swing.JTextField();
        searchField = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        typeOption = new javax.swing.JComboBox();
        checkOnlineButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        notesField.setColumns(20);
        notesField.setRows(5);
        notesField.setText("Notes");
        jScrollPane1.setViewportView(notesField);

        jLabel2.setText("Author *");

        jLabel1.setText("Name *");

        jLabel4.setText("Publisher");

        jLabel3.setText("Publish Year *");

        cancelButton.setText("Cancel");
        cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cancelButtonMouseClicked(evt);
            }
        });

        jLabel6.setText("Category *");

        clearButton.setText("Clear");
        clearButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                clearButtonMouseClicked(evt);
            }
        });

        callNumField.setEditable(false);

        addButton.setText("Add");
        addButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                addButtonMouseClicked(evt);
            }
        });

        jLabel5.setText("Call No");

        jLabel7.setText("ISBN");

        jLabel8.setText("Register Date *");

        regDateField.setToolTipText("dd/mm/yyyy");

        jLabel9.setText("Price");

        categoryOption.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "No Category" }));

        searchField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                searchFieldKeyTyped(evt);
            }
        });

        jLabel10.setText("Search Field");

        jLabel11.setText("Type");

        typeOption.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Book", "DVD", "VCD", "CD" }));

        checkOnlineButton.setText("Check Online");
        checkOnlineButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                checkOnlineButtonMouseClicked(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(jScrollPane1)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(layout.createSequentialGroup()
                                    .add(jLabel1)
                                    .add(59, 59, 59)
                                    .add(nameField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 154, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                        .add(jLabel3)
                                        .add(jLabel4)
                                        .add(jLabel2)
                                        .add(jLabel9))
                                    .add(18, 18, 18)
                                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                        .add(priceField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 154, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                            .add(org.jdesktop.layout.GroupLayout.LEADING, typeOption, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .add(org.jdesktop.layout.GroupLayout.LEADING, authorField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)
                                            .add(org.jdesktop.layout.GroupLayout.LEADING, publishYearField)
                                            .add(org.jdesktop.layout.GroupLayout.LEADING, publisherField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)))))
                            .add(jLabel11))
                        .add(18, 18, 18)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(jLabel5)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .add(callNumField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 154, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .add(layout.createSequentialGroup()
                                .add(1, 1, 1)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(layout.createSequentialGroup()
                                        .add(jLabel7)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(isbnField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 154, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                        .add(jLabel8)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .add(regDateField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 154, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                            .add(layout.createSequentialGroup()
                                .add(addButton)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(clearButton)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .add(cancelButton))
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jLabel6)
                                    .add(jLabel10))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                    .add(searchField)
                                    .add(categoryOption, 0, 154, Short.MAX_VALUE)))
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                .add(0, 0, Short.MAX_VALUE)
                                .add(checkOnlineButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 254, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(nameField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel1)
                    .add(jLabel5)
                    .add(callNumField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(searchField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jLabel10)
                        .add(jLabel11))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, typeOption, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(authorField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel2))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(publishYearField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel3))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(publisherField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel4))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED))
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel6)
                            .add(categoryOption, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel7)
                            .add(isbnField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(checkOnlineButton)
                        .add(6, 6, 6)))
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel9)
                    .add(priceField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(regDateField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel8))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(addButton)
                    .add(clearButton)
                    .add(cancelButton))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 62, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseClicked
        this.dispose();
    }//GEN-LAST:event_cancelButtonMouseClicked

    private void clearButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_clearButtonMouseClicked
        nameField.setText("");
        authorField.setText("");
        typeOption.setSelectedIndex(0);
        publishYearField.setText("");
        publisherField.setText("");
        callNumField.setText("");
        isbnField.setText("");
        regDateField.setText("");
        priceField.setText("");
        categoryOption.setSelectedIndex(0);
        notesField.setText("Notes:");
    }//GEN-LAST:event_clearButtonMouseClicked

    private void addButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addButtonMouseClicked
        Item item = new Item(
            "",
            typeOption.getSelectedItem().toString(),
            nameField.getText(),
            authorField.getText(),
            publishYearField.getText(),
            publisherField.getText(),
            categoryOption.getSelectedItem().toString(),
            isbnField.getText(),
            regDateField.getText(),
            priceField.getText(),
            Macro.ITEM_STATUS_ON_SHELF,
            Macro.ITEM_OWNER_NONE,
            "",
            notesField.getText(),
            Helper.generateID(getDBSession(), Macro.DB_ITEM)
        );
        if (inputCheck(item)){
            String callNumber = callNumGenerator(
                    item.getCategory(), 
                    item.getAuthor(), 
                    item.getPublishYear());
            item.setCallNumber(callNumber);
            String values[] = item.getValues();
            if (!getDBSession().check(Macro.DB_ITEM,
                    String.format("%s='%s' AND %s='%s'",
                        Macro.ITEM_ISBN_L, Codecs.encode(item.getISBN()),
                        Macro.ITEM_NAME_L, Codecs.encode(item.getName())))){
                getDBSession().insert(Helper.encodeValues(values),
                        Macro.DB_ITEM);
                dispose();
                refresh();
            }
            else{
                Prompt.warning("The record already exists.");
            }
        }
    }//GEN-LAST:event_addButtonMouseClicked

    private void searchFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchFieldKeyTyped
        try {
            categoryOption.removeAllItems();
            categoryOption.addItem(Macro.ITEM_CATEGORY_NONE);
            String searchKey = searchField.getText();
            ResultSet rs = getDBSession().search(
                    Macro.DB_CATEGORY, Macro.CATEGORY_NAME_L, Codecs.encode(searchKey));
            while (rs.next()){
                categoryOption.addItem(Codecs.decode(rs.getString(Macro.CATEGORY_NAME_L)));
            }
        } catch (SQLException ex) {
            Logger.getLogger(IM_Add.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_searchFieldKeyTyped
    
    public JSONObject post(String targetURL) {
        JSONObject result = new JSONObject();
        HttpClient client = new DefaultHttpClient();
        HttpUriRequest request = new HttpGet(targetURL);
        HttpResponse response;
        try {
            response = client.execute(request);
            org.apache.http.HttpEntity httpEntity = response.getEntity();
            InputStream is = httpEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            is.close();
            try {
                JSONObject json =
                        (JSONObject)new JSONParser().parse(sb.toString());
                result = json;
            } catch (ParseException ex) {
                Logger.getLogger(
                        IM_Add.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ClientProtocolException e1) {
        } catch (IOException e1) {
        }
        return result;
    }
    
    private void checkOnlineButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_checkOnlineButtonMouseClicked
        String _isbn = isbnField.getText();
        if (!_isbn.equals("")){
            JSONObject result = post(String.format("%s?q=isbn:%s",
                    Macro.GOOGLE_BOOKS_API_ENTRY, _isbn));
            org.json.simple.JSONArray items =
                    (org.json.simple.JSONArray) result.get("items");
            try{
                String author_list = "";
                JSONObject book = (JSONObject)items.get(0);
                JSONObject book_info = (JSONObject) book.get("volumeInfo");
                nameField.setText(book_info.get("title").toString());
                org.json.simple.JSONArray authors = 
                        (org.json.simple.JSONArray) book_info.get("authors");
                for (Object author : authors) {
                    author_list += author.toString();
                    author_list += " ";
                }
                authorField.setText(author_list);
                publishYearField.setText(book_info.get("publishedDate").toString().substring(0, 4));
                regDateField.setText(Helper.getToday());
            }
            catch (NullPointerException e){
                Prompt.warning("The book you search for cannot be found");
            }
        }
        else{
            Prompt.warning("Please enter the ISBN number.");
        }
    }//GEN-LAST:event_checkOnlineButtonMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JTextField authorField;
    private javax.swing.JTextField callNumField;
    private javax.swing.JButton cancelButton;
    private javax.swing.JComboBox categoryOption;
    private javax.swing.JButton checkOnlineButton;
    private javax.swing.JButton clearButton;
    private javax.swing.JTextField isbnField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField nameField;
    private javax.swing.JTextArea notesField;
    private javax.swing.JTextField priceField;
    private javax.swing.JTextField publishYearField;
    private javax.swing.JTextField publisherField;
    private javax.swing.JTextField regDateField;
    private javax.swing.JTextField searchField;
    private javax.swing.JComboBox typeOption;
    // End of variables declaration//GEN-END:variables
}
